package com.wbs.controller;


import com.wbs.model.SysUser;
import com.wbs.service.SysUserService;
import com.wbs.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class UserController {
    // 进行用户的登录
    @Resource
    private SysUserService sysUserService;

    @RequestMapping("/logout.page")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getSession().invalidate();  // 移除session

        String path="sigin.jsp";
        response.sendRedirect(path);

    }

    @RequestMapping("/login.page")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");

        SysUser sysUser=sysUserService.findByKeyword(username);
        String errorMsg="";
        String ret=request.getParameter("ret");  // 查看是否是从别的页面跳转回来的，如果是跳转到原来的页面
        if(StringUtils.isBlank(username)){
            errorMsg="用户名不可以为空";
        }else if (StringUtils.isBlank(password)){
            errorMsg="密码不可以为空";
        }else if(sysUser==null){
            errorMsg="查询不到指定的用户";
        }else if (!sysUser.getPassword().equals(MD5Util.encrypt(password))){
            errorMsg="用户名或者密码错误";
        }else if (sysUser.getStatus()!=1){
            // 冻结的状态时不允许登录的
            errorMsg="用户已经被冻结，请联系管理员";
        }else {
            // login success
            request.getSession().setAttribute("user",sysUser);
            if(StringUtils.isNotBlank(ret)){
                // 如果ret不为空的时候，需要跳转到以前的页面
                response.sendRedirect(ret);
            }else {
                response.sendRedirect("/admin/index.page");
            }
        }
        // login fail
        request.setAttribute("error",errorMsg);
        request.setAttribute("username",username);
        if(StringUtils.isBlank(ret)){
            request.setAttribute("ret",ret);
        }
        String path="signin.jsp";
        request.getRequestDispatcher(path).forward(request,response);


    }
}
